"""
1、什么是中间件 Middleware
   Middleware(中间件) 是介于请求进入与响应返回之间的一段可插拔逻辑，用来处理：
   * 日志记录
   * 请求耗时
   * 权限校验
   * 跨域请求(CORS)
   * 请求频率限制(Rate Limit)

   FastAPI 提供了便捷的方式来自定义中间件，核心是通过装饰器或注册机制封装函数
"""
import time
import logging
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware


# 设置日志输出
logger = logging.getLogger("request_logger")
logger.setLevel(logging.INFO)

handler = logging.StreamHandler()
formatter = logging.Formatter('[%(asctime)s] %(levelname)s: %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)


class RequestTimeMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        start_time = time.time()

        response = await call_next(request)     # 执行请求处理链

        process_time = time.time() - start_time
        formatted_time = f"{process_time * 1000:.2f}ms"

        logger.info(f"{request.method} {request.url.path} - 耗时: {formatted_time}")

        # 可以添加到响应头中返回
        response.headers["X-Process-Time"] = formatted_time
        return response